package com.iwords.android;


import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.os.CountDownTimer;
import android.view.View;

import com.iwords.android.WordIllustration.Sentence;

public class ShowWordCountdown extends CountDownTimer {
	private static ShowWordCountdown fore;
	WordStatus word;
	AnimationView animationView;
	AnimationView.ViewGroup viewGroup;
	Context context;

	//private boolean init;

	public ShowWordCountdown(long millisInFuture, long countDownInterval,
			WordStatus word, AnimationView.ViewGroup viewGroup, AnimationView animationView, Context context) {
		super(millisInFuture, countDownInterval);
		this.word = word;
		this.viewGroup = viewGroup;
		this.animationView = animationView;
		this.context = context;
		if(fore != null){
			fore.cancel();
		}
		fore = this;
		
	}

	@Override
	public void onFinish() {
		//System.out.println(":::::::::::::::ShowWordCountdown.onFinish() ");
		viewGroup.countdown.setText("");
		viewGroup.readingButton.setVisibility(View.VISIBLE);
		
		//viewGroup.sentences.reload();
		IWordsMediaPlayer.getInstance().read(word, context.getResources().getString(R.string.voice));
		animationView.display();
		///loadDictCN();//放在计时器开始时load，有好处也有坏处，但是麻烦
		///loadVar();//加载词形变化部分内容
	}
	//计时开始，则启动加载webview内容的过程，设置标记，避免重复启动
	boolean webViewHasNotLoaded = true;
	
	@Override
	public void onTick(long millisUntilFinished) {
		//System.out.println(":::::::::::::::ShowWordCountdown.onTick() ");
		if(webViewHasNotLoaded){
			this.webViewHasNotLoaded = false;
			this.loadVar();
			this.loadDictCN();
		}
		if (millisUntilFinished / 1000 >= 0)
			viewGroup.countdown.setText(((millisUntilFinished / 1000) + 1) + "s");
	}
	/** 
	 * 获取词形变换。
	 */
	void loadVar() {
		String spelling = word.getSpelling();
		String href = viewGroup.animation_layout.getResources().getString(R.string.var);
		href += spelling.charAt(0) + "/" + CodeUtils.encode(spelling)+".txt";
		HttpPost request = new HttpPost(href);
		//System.out.println("ShowWordCountdown.loadVar() href=" + href);
		//System.out.println("ShowWordLib.loadWordLibs()!");
		try {

			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			//System.out.println("httpResponse.getStatusLine().getStatusCode()="+httpResponse.getStatusLine().getStatusCode());
			if(httpResponse.getStatusLine().getStatusCode()>=400) return;
			// 得到应答的字符串，这也是 JSON 格式保存的数据			
			String retSrc = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
			//System.out.println("ShowWordCountdown.loadVar() retSrc = "+retSrc);
			retSrc = StringEscapeUtils.escapeJavaScript(CodeUtils.decode(retSrc).replaceAll("\n", "<br/>"));
			viewGroup.sentences.loadUrl("javascript:setVariation('"+ retSrc +"');");
			//System.out.println("javascript: setVariation('"+retSrc+"');");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	/** 
	 * 获取并显示dict.cn的词汇解释信息。 
	 * 词汇音标和释义原样显示。
	 * 例句和翻译也原样显示，但增加发音链接，引用Google的web service提供语音支持。
	 */
	void loadDictCN() {
		try {
			//System.out.println("ShowWordCountdown.loadDictCN() word=" + word.getSpelling());
			WordIllustration wordIllustration = ParserDictCNXML.query(word.getSpelling());
			if(wordIllustration == null) return;
			this.animationView.setWordIllustration(wordIllustration);
			String spelling = StringEscapeUtils.escapeJavaScript(wordIllustration.getSpelling());
			String pron = "";
			boolean flag = false;//标记，用来判断是否需要调用更新海词信息的页面，因为有时候所给词汇在海词查不出信息
			if(wordIllustration.getPhonetics() != null){
				pron = StringEscapeUtils.escapeJavaScript(wordIllustration.getPhonetics());
				pron = "["+pron+"]";
				flag = true;
			}
			String meaning = "";
			if(wordIllustration.getMeaning() != null){
				meaning = StringEscapeUtils.escapeJavaScript(wordIllustration.getMeaning().replaceAll("\n", "<br/>"));
				flag = true;
			}
			//System.out.println("ShowWordCountdown.loadDictCN() $$$$$$$$$$$$ ViewGroup viewGroup.flag="+viewGroup.flag+" spelling="+spelling);
			//System.out.println("ShowWordCountdown.loadDictCN() $$$$$$$$$$$$ ViewGroup viewGroup.sentences="+viewGroup.sentences);
			if(flag) viewGroup.sentences.loadUrl("javascript:setWordSpelling('"+spelling+"','"+pron+"','"+meaning+"');");
			//System.out.println("viewGroup.sentences.loadUrl(\"javascript:setWordSpelling('"+wordIllustration.getSpelling()+"','"+wordIllustration.getPhonetics()+"','"+wordIllustration.getMeaning()+"');");
			
			List<Sentence> sentences = wordIllustration.getSentences();
			int index = 0;
			for(Sentence sentence : sentences){
				//System.out.println("$$$$$$$$$$$$"+index+" sen:"+sentence.en);
				String cn = StringEscapeUtils.escapeJavaScript(sentence.cn);
				String en = StringEscapeUtils.escapeJavaScript(sentence.en);
				viewGroup.sentences.loadUrl("javascript:setSentence("+index+++",'"+en+"','"+cn+"');");
			}
			//System.out.println("ShowWordCountDown.loadDictCN() viewGroup.sentences.getId()="+viewGroup.sentences.getId());
			//System.out.println("ShowWordCountDown.loadDictCN() viewGroup.sentences.getId()="+viewGroup.spelling.getText());
			//System.out.println("ShowWordCountDown.loadDictCN() viewGroup.sentences.getVisibility()="+viewGroup.sentences.getVisibility());
			
			//System.out.println("ShowWordCountDown.loadDictCN() viewGroup.sentences.getId()="+viewGroup.sentences.getId());
			//System.out.println("ShowWordCountDown.loadDictCN() viewGroup.sentences.getVisibility()="+viewGroup.sentences.getVisibility());
		} catch (Exception e) {
			//e.printStackTrace();
			System.out.println("Error: "+e.getMessage());
		}
	}
}
